<script lang="ts" setup>
import type { TableColumn, AlignType } from "@/types/table";
import defaultStyle from "@/config/defaultConfig";
import { useUrlDictStore } from "@/store";
import { getDicurlMap } from "@/utils";
import CommonTag from "@/components/CommonTag.vue";

defineOptions({
  name: "DetailDesc",
  inheritAttrs: false,
});

const props = withDefaults(
  defineProps<{
    columns: TableColumn[];
    rowData: Record<string, unknown>;
    descLabelWidth?: number | string;
    descAlign?: AlignType;
    descLabelAlign?: AlignType;
  }>(),
  {
    descLabelWidth: defaultStyle.DescLabelWidth,
    descAlign: defaultStyle.DescAlign,
    descLabelAlign: defaultStyle.DescLabelAlign,
  }
);

const { dictData } = useUrlDictStore();

const renderContent = (column: TableColumn) => {
  const {
    prop,
    tag,
    type,
    dicData,
    dicUrl,
    multiple,
    props: labelMap,
    formatter: _formatter,
    colorDict,
  } = column;
  let cellValue = props.rowData[prop!] as string;
  if ("select" === type || "tree" === type) {
    let key = labelMap?.value ?? "value";
    let val = labelMap?.label ?? "label";
    let map: Record<string, string> = {};
    if (dicData) map = Object.fromEntries(dicData.map((item) => [item[key], item[val]]));
    if (dicUrl) map = getDicurlMap(dictData.get(dicUrl), key, val);
    if (tag) {
      return h(CommonTag, { value: cellValue, labelDict: map, colorDict });
    } else {
      return () =>
        multiple
          ? cellValue
              .split(",")
              .map((i) => map[i])
              .join("  ")
          : map[cellValue];
    }
  }

  return () => cellValue;
};
</script>
<template>
  <el-descriptions :column="24" size="large" :label-width="descLabelWidth" border>
    <el-descriptions-item
      v-for="(column, index) in columns"
      :key="index"
      :label-align="descLabelAlign"
      :align="descAlign"
      :label="column.label"
      :span="column.span ?? defaultStyle.Span"
      :width="descLabelWidth"
    >
      <component :is="renderContent(column)"></component>
    </el-descriptions-item>
  </el-descriptions>
</template>
<style lang="scss" scoped></style>
